package com.qining618.cms.ucenter.controller.admin;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.qining618.cms.ucenter.controller.admin.request.AdminMenuEditRequest;
import com.qining618.cms.ucenter.domain.Menu;
import com.qining618.cms.ucenter.service.MenuService;
import com.qining618.common.annotation.Access;
import com.qining618.common.result.ApiResult;
import com.qining618.common.result.TableData;
import com.qining618.common.utils.Query;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Description;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

/**
 * <p>
 * 菜单 前端控制器
 * </p>
 *
 * @author qining
 * @since 2019-09-16
 */
@RestController
@RequestMapping("/admin/api/ucenter/menu")
public class AdminMenuController {

    @Autowired
    private MenuService menuService;

    @Access(needAdmin = true)
    @GetMapping(value = "page")
    @Description("分页")
    public ApiResult page(@RequestParam Map<String, Object> params) {
        IPage<Menu> pageInfo = menuService.page(params);
        return ApiResult.ok(TableData.of(pageInfo));
    }

    @Access(needAdmin = true)
    @GetMapping(value = "list")
    @Description("列表")
    public ApiResult list(@RequestParam Map<String, Object> params) {
        Query<Menu> query = new Query<>(params);

        List<Menu> menuList = menuService.list(query.getQueryWrapper());

        return ApiResult.ok(menuList);
    }

    @Access(needAdmin = true)
    @GetMapping("tree")
    @Description("查询列表（树）")
    public ApiResult findTree() {
        List<Menu> menuList = menuService.tree();
        return ApiResult.ok(menuList);
    }

    @Access(needAdmin = true)
    @PostMapping
    @Description("添加")
    public ApiResult add(@RequestBody @Validated AdminMenuEditRequest menuEditRequest) {
        Menu menu = menuService.add(menuEditRequest.getCode(), menuEditRequest.getName(),
                menuEditRequest.getType(), menuEditRequest.getParentId());
        return ApiResult.ok(menu);
    }

    @Access(needAdmin = true)
    @PutMapping(value = "{id}")
    @Description("编辑")
    public ApiResult edit(
            @PathVariable(value = "id") Long id,
            @RequestBody @Validated AdminMenuEditRequest menuEditRequest) {
        Menu menu = menuService.edit(id, menuEditRequest.getCode(), menuEditRequest.getName(),
                menuEditRequest.getType(), menuEditRequest.getParentId());
        return ApiResult.ok(menu);
    }

    @Access(needAdmin = true)
    @DeleteMapping(value = "{id}")
    @Description("删除")
    public ApiResult delete(
            @PathVariable(value = "id") Long id) {
        menuService.deleteById(id);
        return ApiResult.ok();
    }
}

